// 模拟加载图片的异步函数
function loadImage(url) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve(url);
    img.onerror = () => reject(url);
    img.src = url;
  });
}

// 控制并发量的函数
function loadImagesWithLimit(urls, limit) {
  let index = 0;
  let activePromises = 0;
  const results = [];

  return new Promise((resolve, reject) => {
    function enqueue() {
      if (index >= urls.length && activePromises === 0) {
        resolve(results);
        return;
      }

      while (activePromises < limit && index < urls.length) {
        activePromises++;
        const currentIndex = index;
        loadImage(urls[currentIndex])
          .then((result) => {
            results[currentIndex] = result;
          })
          .catch((error) => {
            results[currentIndex] = error;
          })
          .finally(() => {
            activePromises--;
            enqueue();
          });
        index++;
      }
    }

    enqueue();
  });
}

// 测试用例
const imageUrls = [
  "https://example.com/image1.jpg",
  "https://example.com/image2.jpg",
  "https://example.com/image3.jpg",
  "https://example.com/image4.jpg",
  "https://example.com/image5.jpg",
  "https://example.com/image6.jpg",
  "https://example.com/image7.jpg",
  "https://example.com/image8.jpg",
  "https://example.com/image9.jpg",
  "https://example.com/image10.jpg",
];

loadImagesWithLimit(imageUrls, 3)
  .then((results) => {
    console.log("All images loaded:", results);
  })
  .catch((error) => {
    console.error("Error loading images:", error);
  });
